package com.chapter.sample.answer.multiplex;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class MyData_Local {

    ThreadLocal<Integer> threadLocalField = ThreadLocal.withInitial(() -> 3);

    public void add() {
        threadLocalField.set(threadLocalField.get() + 1);
    }
}

public class ThreadLocalDemoV2 {
    public static void main(String[] args) {
        MyData myData = new MyData();
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            for (int i = 1; i <= 10; i++) {
                threadPool.submit(() -> {
                    try {
                        Integer before = myData.threadLocalField.get();
                        myData.add();
                        Integer after = myData.threadLocalField.get();

                        System.out.println(Thread.currentThread().getName() + " " + before + " x " + after);
                    } finally {
                        myData.threadLocalField.remove();
                    }
                });
            }
        } finally {
            threadPool.shutdown();
        }
    }
}
